import CryptoJS from 'crypto-js'

const IAWEB = {
  key: '12345645678iaweb',
  iv: '1234567812345678'
}

let AuthTokenKey = CryptoJS.enc.Latin1.parse('12345645678iaweb'); //AES密钥
let AuthTokenIv = CryptoJS.enc.Latin1.parse('1234567812345678'); //AES向量
interface IAes {
  parse: any;
  encrypt: any;
  decrypt: any;
}

class Aes<IAes> {
  static parse(data: string) {
    return CryptoJS.enc.Latin1.parse(data);
  }

  // AES加密
  static encrypt(data: string | object, key?: string, iv?: string) {
    let dataStr = JSON.stringify(data);
    let encrypted = CryptoJS.AES.encrypt(dataStr, AuthTokenKey, {
        iv: AuthTokenIv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding
    });
    console.log('0000',dataStr);
    console.log('11111',encrypted.toString());
    console.log('222',Aes.decrypt(encrypted.toString()));
    return encrypted.toString();
  }

  // AES解密
  static decrypt(data: string | object, key?: string, iv?: string) {
    try {
      const decrypted = CryptoJS.AES.decrypt(data, this.parse(key || IAWEB.key) || AuthTokenKey, {
        iv: this.parse(iv || IAWEB.iv) || AuthTokenIv,
        padding: CryptoJS.pad.ZeroPadding
      });
      return decrypted.toString(CryptoJS.enc.Utf8);
    } catch (e) {
      return data;
    }
  }
}

export default Aes;
